package nl.project.system;

import java.io.IOException;
import java.util.HashMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import nl.project.data.Employee;
import nl.project.data.Parent;
import nl.project.data.Student;
import nl.project.data.Teacher;
import nl.project.data.User;

@SuppressWarnings("serial")
public class Dashboard extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		HttpSession session = req.getSession();
		try {
			// Try to get required session attributes.
			// A NullPointerException will be thrown if one is not set.
			session.getAttribute("user").toString();
			session.getAttribute("links").toString();
			resp.sendRedirect("/dashboard.jsp");
		} catch (NullPointerException e) { //Either user of links are not set in session...
			try {
				User user = (User) session.getAttribute("user");
				user.toString();
				HashMap<String, String> links = generateLinks(user);
				session.setAttribute("links", links);
				getServletContext().getRequestDispatcher("dashboard.jsp").forward(req, resp);
			} catch (NullPointerException ex) {
				// No user set! Send to login page!
				resp.sendRedirect("");
			}
		}
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}
	
	/*
	 * Generate the links that can be user by the logged in user.
	 * Example: a parent is allowed to use the planner, but is not allowed
	 * to submit any information on the noticeboard (only teachers and employees)
	 * are allowed to do that).
	 */
	private HashMap<String, String> generateLinks(User user) {
		HashMap<String, String> links = new HashMap<String, String>();
		if (user instanceof Parent) {
			links.put("Ouderavond planner", "/planner");
			//links.put("Mededelingen", "/notices");
		} else if (user instanceof Student) {
			//links.put("Mededelingen", "/notices");
		} else if (user instanceof Teacher) {
			//links.put("Mededelingen", "/notices");
			//links.put("Mededeling posten", "/notices_submit");
			links.put("Overzicht van leerlingen op de kaart", "/Overzicht");
			links.put("Overzicht prestaties van leerlingen", "/statsSelect.jsp");
		} else if (user instanceof Employee) {
			//links.put("Mededelingen", "/notices");
			//links.put("Mededeling posten", "/notices_submit");
			links.put("Ouderavond planning starten", "/start_planner.jsp");
			links.put("Plan afspraak voor ouder", "/planner");
			links.put("Overzicht prestaties van leerlingen", "/statsSelect.jsp");
			if (getServletContext().getAttribute("GoogleMaps") == null) {
				links.put("Create Google Maps", "/CreateGoogleMaps");
			}
		}
		return links;
	}
}